<template>
  <view class="pay">
    <view v-if="shippingAddress"
          class="pay-contact">
      <view class="address u-line-2">{{shippingAddress.provinceName}}{{shippingAddress.cityName}}{{shippingAddress.countyName}}{{shippingAddress.detailInfo}}</view>
      <view class="contact">{{shippingAddress.userName}}：<text>{{shippingAddress.telNumber}}</text></view>
    </view>
    <view v-else
          class="selected-address">
      <view @click="handleSelectAddress"
            class="selected-address-btn">选择地址</view>
    </view>
    <view class="selected-goods">
      <view class="selected-goods-title">已选商品</view>
      <u-button v-if="!cartList.length"
                @click="handleToIndex">没有商品哦！可以去首页看看</u-button>
      <view v-else
            class="selected-goods-list">
        <view class="selected-goods-item"
              v-for="item in cartList"
              :key="item.goods.id">
          <view class="selected-goods-img">
            <u-image :src="item.goods_small_logo"
                     height="191rpx"
                     width="191rpx"
                     mode="widthFix"></u-image>
          </view>
          <view class="selected-goods-content">
            <view class="selected-goods-name u-line-2">{{item.goods_name}}</view>
            <view class="selected-goods-count">
              <view class="selected-goods-price">￥{{item.goods_price}}</view>
              <view class="selected-goods-num">✖ {{item.nums}}</view>
            </view>
          </view>
        </view>

      </view>
    </view>
    <Settlement>
      <template v-slot:left>
        <view class="left">
          <view class="total">合计：<text class="sign">￥</text><text>{{totalPrice}}</text></view>
          <view class="freight">运费：￥{{totalPrice?0:10}}<view>
            </view>

      </template>
      <template v-slot:right>
        <view :class="['goPay',num?'':'no-goods']"
              @click="handlePay">去支付({{num}})</view>
      </template>
    </Settlement>
  </view>
</template>

<script>
import { mapState } from 'vuex'
export default {
  computed: {
    //   获取vuex仓库中的数据
    ...mapState({
      shippingAddress: (state) => state.user.shippingAddress,
      cartList: (state) =>
        state.cart.cartList.filter((item) => item.isSelected),
      token: (state) => state.user.token,
    }),
    // 获取商品数据
    num() {
      return this.cartList.reduce((count, item) => (count += item.nums), 0)
    },
    // 获取商品总价格
    totalPrice() {
      return this.cartList.reduce(
        (count, item) => (count += item.nums * item.goods_price),
        0
      )
    },
  },
  methods: {
    //   跳转到首页
    handleToIndex() {
      uni.switchTab({ url: '/pages/index/index' })
    },
    //   选择地址
    async handleSelectAddress() {
      if (!this.token) {
        uni.navigateTo({
          url: '/pages/WeChatAuthorization/WeChatAuthorization',
        })
        return false
      }
      const [err, shippingAddress] = await uni.chooseAddress()
      if (err !== null) {
        uni.showToast({ title: '选择收货地址失败', icon: 'error' })
        return
      }
      console.log(shippingAddress)
      this.$store.commit('user/setShippingAddress', shippingAddress)
    },
    //   微信支付功能
    async handlePay() {
      if (!this.token) {
        uni.navigateTo({
          url: '/pages/WeChatAuthorization/WeChatAuthorization',
        })
        return false
      }
      //  订单总价格
      const order_price = this.totalPrice || 10
      //  收货地址
      let consignee_addr = `${this.shippingAddress.provinceName}${this.shippingAddress.cityName}${this.shippingAddress.countyName}${this.shippingAddress.detailInfo}`
      //  创建订单
      const createOrder = { order_price, consignee_addr, goods: this.cartList }
      //  获取订单编号
      const { order_number } = await this.$u.post(
        '/my/orders/create',
        createOrder
      )
      //   获取支付参数
      const { pay } = await this.$u.post('/my/orders/req_unifiedorder', {
        order_number,
      })
      //   获取服务提供商参数
      const [err, providerData] = await uni.getProvider({ service: 'payment' })
      const { provider } = providerData
      // orderInfo: 'orderInfo', //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
      // const PayData = { provider , orderInfo , timeStamp , package , signType , paySign , nonceStr}
      await uni.requestPayment({ ...pay, orderInfo: 'orderInfo', provider })
    },
  },
}
</script>

<style lang="scss" scoped>
.no-goods {
  background-color: #ccc !important;
}
.pay {
  height: 100vh;
  padding: 20rpx;
  background-color: #f9f9f9;
  .pay-contact {
    margin-bottom: 40rpx;
    border-radius: 10rpx;
    background-color: #fff;
    padding: 16rpx 17rpx 16rpx 29rpx;
    .address {
      font-weight: 700;
      margin-bottom: 18rpx;
    }
  }
  .selected-address {
    position: relative;
    width: 711rpx;
    height: 187rpx;
    margin-bottom: 18rpx;
    background-color: #fff;
    .selected-address-btn {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 303rpx;
      font-weight: 700;
      color: #ea4350;
      line-height: 89rpx;
      text-align: center;
      border-radius: 89rpx;
      border: 2px solid #ea4350;
      transform: translate(-50%, -50%);
    }
  }
  .selected-goods {
    padding: 10rpx 15rpx;
    background-color: #fff;
    .selected-goods-title {
      font-weight: 700;
      padding: 7rpx 11rpx;
      margin-bottom: 20rpx;
    }
    .selected-goods-item {
      display: flex;
      padding-bottom: 5rpx;
      margin-bottom: 10rpx;
      border-bottom: 1px solid #ccc;
      .selected-goods-img {
        flex: 1;
        width: 191rpx;
        height: 191rpx;
      }
      .selected-goods-content {
        flex: 2;
        display: flex;
        padding: 0 10rpx;
        flex-direction: column;
        justify-content: space-around;
        .selected-goods-count {
          display: flex;
          justify-content: space-between;
          .selected-goods-price {
            color: red;
          }
        }
      }
    }
  }
  .left {
    display: flex;
    font-size: 30rpx;
    align-items: center;
    font-weight: 700;
    text {
      color: $themeColor;
    }
    .sign {
      font-size: 24rpx;
    }
    .freight {
      margin-left: 20rpx;
    }
  }
  .goPay {
    width: 150rpx;
    color: #fff;
    font-size: 24rpx;
    text-align: center;
    line-height: 52rpx;
    border-radius: 52rpx;
    background-color: $themeColor;
  }
}
</style>